//
//  Account.m
//  iMoney
//
//  Created by VertigoSol on 9/11/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "Account.h"

@implementation Account
@synthesize expenses, accountName, totalAmount, date;
@synthesize offsetAmount;
@synthesize type;

-(id)initWithName:(NSString*)aName
{
	if(self = [super init])
	{
		expenses = [[NSMutableArray alloc] init];
		self.accountName = [aName copy];
		totalAmount =0;
		dirty = NO;
	}
	
	return self;
}

-(id)initWithNameOffsetAmount:(NSString*)aName:(float) aOffsetAmount
{
	if(self = [self initWithName:aName])
	{
		offsetAmount = aOffsetAmount;
	}
	
	return self;
}

-(id)init
{
	if(self = [super init])
	{
		expenses = [[NSMutableArray alloc] init];
		self.accountName = @"NO Name";
		totalAmount =0;
		dirty = NO;
	}
	
	return self;
}

-(void)addExpenseFront:(Expense*)expense
{
 	[expenses insertObject:expense atIndex:0];
	totalAmount = totalAmount+ [expense amount];
	dirty = YES;
}


-(void)addExpense:(Expense*)expense:(BOOL) dateSorted
{
	//we dont care just stick at the front of the list
	if(!dateSorted){
		[self addExpenseFront:expense];
	}
	else{
	
		BOOL found= NO;
		int index = 0;
		for(; index< [expenses count]; index++)
		{
			//newest date is at the top
			if([[expense date] timeIntervalSince1970] >= [[[expenses objectAtIndex:index] date] timeIntervalSince1970] )
			{
				[expenses insertObject:expense atIndex:index];
				found = YES;
				break;
			}
			
		}
		
		//add to the tail end of the list
		if(!found)
			[expenses addObject:expense];
		
		totalAmount = totalAmount+ [expense amount];
		dirty = YES;
		
	}

	
	
}

-(void)removeExpense:(Expense*) expense
{
	for(int i=0; i < [expenses count] ;i++)
	{
		if([expense equals:[expenses objectAtIndex:i]])
		{
			[expenses removeObjectAtIndex:i];
		}
	}
	
}

-(void)removeExpenseAtIndex:(int)index
{
	totalAmount = totalAmount - [[expenses objectAtIndex:index] amount];
	[expenses removeObjectAtIndex:index];
}

-(Expense*) getExpense:(int) index
{
	return [expenses objectAtIndex:index];
}


-(NSMutableDictionary*) getExpensesAsDateDic
{
	NSMutableDictionary* dic = [NSMutableDictionary new];
	
	for(Expense* e in expenses)
	{
		NSString* key = [NSString stringWithFormat:@"%f", [e.date timeIntervalSince1970]];
		NSMutableArray* dates = [dic valueForKey:key];
		if(dates ==nil)
		{
			NSMutableArray* vals = [NSMutableArray new];
			[vals addObject:e];
			[dic setValue:vals forKey:key];
		}
		else
		{
			[dates addObject:e];
		}
	}
	
	return dic;
	
}

-(void) updateAmount
{
	totalAmount =0;
	
	for(Expense* e in  expenses)
	{
		totalAmount+=[e amount];
	}
	
}


-(int) count
{
	return [expenses count];
}

-(NSEnumerator *) objectEnumerator
{
	return [expenses objectEnumerator];
}

-(void)dealloc
{	
	[date release];
	[accountName release];
	[expenses release];
	[super dealloc];
}



@end
